def smart_getattr(object, dotted_str, stop_before=0):
    """
    This is a variation on the normal getattr.
    It differs in that it follows dotted relationships
    and can return the object gotten n before the end,
    where n is the integer specified as stop_before.

    e.g.
    from django.db import models
    from datetime import datetime
    class Poll(models.Model):
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published')

    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)

    >>> p = Poll(question = "Do you read?", pub_date = datetime.now())
    >>> p.save()
    >>> c = Choice(poll = p, choice = "Yes")
    >>> smart_getattr(c, 'poll.id')
    1
    >>> smart_getattr(c, 'poll.question')
    "Do you read?"
    >>> smart_getattr(c, 'poll.question', stop_before = 1)
    <Poll: Poll object>
    >>> smart_getattr(c, 'poll.question', stop_before = 2)
    <Choice: Choice object>
    >>> smart_getattr(c, 'poll')
    <Poll: Poll object>
    >>> smart_getattr(c, 'poll', stop_before = 1)
    <Choice: Choice object>
    """
    attributes_to_get = dotted_str.split('.')
    history = [object,]
    current = object
    for attribute in attributes_to_get:
        current = getattr(current, attribute)
        history.append(current)
    try:
        return history[len(history)-stop_before-1]
    except:
        return current